﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
//
using System.IO;
using System.Net;
//
using ArgumentsParser;
/*
Copyright 2011 Mirosław M. Mączka

This file is part of MobiLang.

    MobiLang is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Foobar is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/
namespace MobiLang
{
    static class Program
    {
        //
        private static int lcidLocale = 0, lcidInputLanguage = 0, lcidOutputLanguage = 0;
        private static bool setFileName = false;
        private static int argsBase = 0;

        //
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if (0 == args.Length)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
                return;
            }
            //
            //
            using (ConsoleInitialization.ConsoleInitialization CI = new ConsoleInitialization.ConsoleInitialization())
            {
                ArgsParser ap = new ArgsParser("-Locale:", "-Input_Language:", "-Output_Language:", "-rename", "-list", "-h", "-?");
                try
                {
                    ap.Parse(args);
                    //ap.Parse(new[] { "-h", "aaa"});
                }
                catch (Exception e)
                {
                    Console.WriteLine("ERROR: parameter [{0}]", e.Message);
                    return;
                }
                argsBase = ap.TotalArgsCount;
                //
                if (ap.ArgExists("-h") || ap.ArgExists("-?"))
                {
                    Usage();
                    return;
                }

                if (ap.ArgExists("-list"))
                {
                    LanguageCodes.ShowAll();
                    return;
                }
                //
                if (ap.ArgExists("-rename"))
                {
                    setFileName = true;
                }
                //
                if (ap.ArgExists("-Locale:"))
                {
                    lcidLocale = LanguageCodes.GetCultureLCID((ap.ArgValue("-Locale:")));
                    if (0 == lcidLocale)
                    {
                        Console.WriteLine("ERROR: invalid language [{0}]", ap.ArgValue("-Locale:"));
                        return;
                    }
                }
                //
                if (ap.ArgExists("-Input_Language:"))
                {
                    lcidInputLanguage = LanguageCodes.GetCultureLCID((ap.ArgValue("-Input_Language:")));
                    if (0 == lcidInputLanguage)
                    {
                        Console.WriteLine("ERROR: invalid language [{0}]", ap.ArgValue("-Input_Language:"));
                        return;
                    }
                }
                //
                if (ap.ArgExists("-Output_Language:"))
                {
                    lcidOutputLanguage = LanguageCodes.GetCultureLCID((ap.ArgValue("-Output_Language:")));
                    if (0 == lcidOutputLanguage)
                    {
                        Console.WriteLine("ERROR: invalid language [{0}]", ap.ArgValue("-Output_Language:"));
                        return;
                    }
                }
                //
                if (0 != lcidLocale) Console.WriteLine("Locale: {0}", LanguageCodes.ToText(lcidLocale));
                if (0 != lcidInputLanguage) Console.WriteLine("Input_Language: {0}", LanguageCodes.ToText(lcidInputLanguage));
                if (0 != lcidOutputLanguage) Console.WriteLine("Output_Language: {0}", LanguageCodes.ToText(lcidOutputLanguage));
                //
                if (argsBase == args.Length) { Usage(); return; }

                MobiHandler mh = new MobiHandler();
                try
                {
                    for (int i = argsBase; i < args.Length; i++)
                    {
                        string[] expandedFiles = expandWildcards(args[i]);
                        foreach (string f in expandedFiles)
                        {
                            if (!File.Exists(f))
                            {
                                Console.WriteLine("ERROR: Can't open file [{0}]", f);
                                continue;
                            }
                            mh.FileName = f;
                            mh.ReadHeader();
                            
                            if (0 != lcidLocale) mh.SetLangLocal(lcidLocale);
                            if (0 != lcidInputLanguage) mh.SetLangInputLanguage(lcidInputLanguage);
                            if (0 != lcidOutputLanguage) mh.SetLangOutputLanguage(lcidOutputLanguage);
                            //
                            if (setFileName) mh.RenameFile();
                        }
                    }
                }
                catch (Exception e)
                {
                    Clipboard.SetText(e.Message);
                    Console.WriteLine("ERROR: {0}", e.Message);
                }
                //
            }
            return;
            //
        }
            //
        static string[] expandWildcards(string pathName)
        {
            string[] fNames;
            //
            try
            {
                string dir = Path.GetDirectoryName(pathName);
                if ("" == dir) dir = ".";
                //
                fNames = Directory.GetFiles(dir, Path.GetFileName(pathName));
                if (0 == fNames.Length) return new string[] { pathName };
            }
            catch
            {
                return new string[] { pathName };
            }
            //
            return fNames;
        }

        private static void Usage()
        {
            if (1045 == LanguageCodes.CurrentLCID())
            {
                Console.WriteLine();
                Console.WriteLine("Zastosowanie: {0} [-Locale value] [-Input_Language value] [-Output_Language value] [-rename] [-h] plik_mobi_prc...", Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]));
                Console.WriteLine("-h : Pomoc");
                Console.WriteLine("-list : Pokaż wszystkie kody językowe");
                Console.WriteLine("-Locale: język książki");
                Console.WriteLine("-Input_Language : język wejściowy dla słownika");
                Console.WriteLine("-Output_Language : język wyjściowy dla słownika");
                Console.WriteLine("value : kod języka, jako tekst albo liczna (np. 'pl' 'pl-pl' '21' '1045')");
                Console.WriteLine("-rename : Zmień nazwę pliku na taką jak w polu Full_Name");
                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine("Usage: {0} [-Locale value] [-Input_Language value] [-Output_Language value] [-rename] [-h] file_mobi_prc...", Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]));
                Console.WriteLine("-h : Help");
                Console.WriteLine("-list : Show all language codes");
                Console.WriteLine("-Locale: Book locale code");
                Console.WriteLine("-Input_Language : Input language for a dictionary");
                Console.WriteLine("-Output_Language : Output language for a dictionary");
                Console.WriteLine("value : languade code, number or text (for example 'en' 'en-us' '9' '1033')");
                Console.WriteLine("-rename : Rename file as in field Full_Name");
                Console.WriteLine("");
            }
        }
            //
            //
        
    }
}
